package gui;

import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;

import core.ViewableEntity;

public abstract class EntityRenderer {

	// the minimum rotation that might be visible.
	private final float MIN_ROT = .001f;

	/**
	 * Renders the given entity with the given graphics context.
	 */
	public void render(ViewableEntity e, Graphics2D g) {
		if (Math.abs(e.velocityHeading) > MIN_ROT) {
			renderRotated(e, g);
		} else {
			draw(e, g);
		}
	}

	/**
	 * Transforms the graphics context before the render so that the entity is
	 * drawn with the heading in mind. Afterwards, the transformation is undone.
	 */
	protected final void renderRotated(ViewableEntity e, Graphics2D g) {
		AffineTransform original = g.getTransform();
		AffineTransform rotated = new AffineTransform(original);
		rotated.rotate(-e.velocityHeading, e.x + e.width / 2, e.y + e.height
				/ 2);
		g.setTransform(rotated);
		draw(e, g);
		g.setTransform(original);
	}

	/**
	 * Does the actual rendering of the entity.
	 */
	protected abstract void draw(ViewableEntity e, Graphics2D g);

}
